﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using Kaskelot.SP.Core;
using Kaskelot.SP.Model.Client.Forms;
using Microsoft.SharePoint;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientPersonHandelseLoggExtensions
	{
		public static ClientPersonHandelseLogg ToClientContract(this PersonHandelseLogg entity)
		{
			ClientPersonHandelseLogg b = new ClientPersonHandelseLogg();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientPersonHandelseLogg ToMinimalClientContract(this PersonHandelseLogg entity)
		{
			ClientPersonHandelseLogg b = new ClientPersonHandelseLogg();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static PersonHandelseLogg ToContract(this ClientPersonHandelseLogg b)
		{
			PersonHandelseLogg entity = new PersonHandelseLogg();

			CopyToEntity(b, entity);

			return entity;
		}

        public static PersonHandelseLogg UpdateContract(this PersonHandelseLogg phl, HandelseLoggForm form)
        {
			if (phl.Id == Guid.Empty)
				phl.Id = Guid.NewGuid();

            phl.UppfoljningKravs = form.AtgardKravs;
            phl.PersonId = new Guid(form.ParentId);
            phl.Text = form.Text;
            phl.Datum = DateTime.Parse(form.Datum);

			phl.Andrad = DateTime.Now;
			phl.AndradAv = SPContext.Current.Web.CurrentUser.Name;

            return phl;
        }

		private static void CopyFromEntity(PersonHandelseLogg from, ClientPersonHandelseLogg to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;

			to.PersonId = from.PersonId;
			to.Text = from.Text;
			to.UppfoljningKravs = from.UppfoljningKravs.ToJaNej();
            to.Datum = from.Datum.ToString("yyyy-MM-dd");
			to.Andrad = from.Andrad.ToString(String.Empty);
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad.ToShortDateString();
			to.SkapadAv = from.SkapadAv;
		}

		private static void CopyToEntity(ClientPersonHandelseLogg from, PersonHandelseLogg to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;

			to.PersonId = from.PersonId;
			to.Text = from.Text;
			to.UppfoljningKravs = from.UppfoljningKravs.FromJaNej();

			to.Andrad = DateTime.Parse(from.Andrad);
			to.AndradAv = from.AndradAv;
			to.Skapad = DateTime.Parse(from.Skapad);
			to.SkapadAv = from.SkapadAv;
		}
	}
}
